package com.bw.mvvm_common.mvvm.network.inteceptor;



import com.bw.mvvm_common.mvvm.utils.SignUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

public
/**
 * @author Guan
 * @description:
 * @date :2021/9/8 0008 下午 4:12
 *
 */
class SignInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Request.Builder builder = new Request.Builder();
        builder.url(request.url());
        builder.headers(request.headers());

        RequestBody body = request.body();
        if (body==null){
            return chain.proceed(request);
        }
        Buffer buffer = new Buffer();
        body.writeTo(buffer);

        byte[] buff = new byte[1024];

        String json = "";
        while (buffer.read(buff)!=-1){
            json+=new String (buff);
        }
        buffer.flush();
        buffer.close();

        String value="";

        String result="";
        try {
            JSONObject job = new JSONObject(json);
            Iterator<String> it  = job.keys();
            while (it.hasNext()){
                value+=job.getString(it.next());


            }

            String sign = SignUtils.createSign(value);
            job.put("sign",sign);
            result = job.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),result);
        builder.post(requestBody);

        return chain.proceed(builder.build());
    }
}
